#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ""
__author__ = "Administrator"
__mtime__ = "2016/6/17"
"""
# 合并日志文件并按照时间排序。


import time, os, re


def get_timestamp(dir):
    list = []
    with open(dir) as f:
        for line in f.xreadlines():
            str_time = line.split(',')[0]
            time_stamp = time.mktime(time.strptime(str_time, "%Y-%m-%d %H:%M:%S"))
            list.append(time_stamp)
    return list


list1 = get_timestamp(r'D:\log\access1.log')
list2 = get_timestamp(r'D:\log\access2.log')
list1 += list2
list1.sort()

com = re.compile('\w+.log')


# 一定注意变和不变，当增加条件因子变化时，一定要注意排除掉。



def read_every_file(log_dir):
    for ii in range(len(list1)):
        file_list = " ".join(os.listdir(log_dir))
        file_mem = com.findall(file_list)
        for i in range(len(file_mem)):
            os.chdir(log_dir)
            file_abs_dir = os.path.abspath(file_mem[i])
            with open(file_abs_dir) as f:
                for line in f.xreadlines():
                    str_time = line.split(',')[0]
                    time_stamp = time.mktime(time.strptime(str_time, "%Y-%m-%d %H:%M:%S"))
                    if list1[ii] == time_stamp:
                        new_file = open('new.txt', 'a')
                        new_file.write(line)
                        # time.sleep(2)

    new_file.close()


read_every_file(r'D:\log')
